package com.yjz.middleware.redis;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author :yuanJinZhong
 * @description:Redisson 实现分布式锁
 * @date :2018/7/31-13:37
 */
@Slf4j
public class RedissonDistributLock {

    @Test
    public void distributLockTest() {
        //Redisson连接配置文件
        Config config = new Config();
        config.useClusterServers().addNodeAddress("redis://127.0.0.1:30001","redis://127.0.0.1:30002","redis://127.0.0.1:30003");
        //config.useSingleServer().setAddress("redis://127.0.0.1:30001");
        RedissonClient redisson = Redisson.create(config);
        // 1.获得锁对象实例 RedissonLock
        RLock yuxinLock = redisson.getLock("yuXinLock{1}");// {1}为hashTag，redis内部会取出{}里面的1，进行CRC16_hash（1）%16384 得到slot,等价于将key固定到指定的slot
//
//        // 1.watchDog 只有在未显示指定加锁时间时才会生效。（这点很重要）
//        yuxinLock.lock();
//
//        yuxinLock.unlock();

      /*  while (true) {
         //当前客户端一直连接着，则锁会一直续约（前提获取锁时候没有设置超时时间）
        }
*/
          testM(yuxinLock);

        while (true) {

        }
    }

    public void testM(RLock yuxinLock) {
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 2; i++) {
            fixedThreadPool.execute(new Task("woker_" + i, yuxinLock));
        }
    }


    class Task implements Runnable {

        private String name;
        private RLock yuxinLock;

        public Task(String name, RLock yuxinLock) {
            this.name = name;
            this.yuxinLock = yuxinLock;
            System.out.println(name);
        }

        public void run() {
            boolean res = false;
            try {
                System.out.println(name + "开始夺锁大战");
                //1.不支持过期自动解锁，不会超时
                yuxinLock.lock();
                System.out.println(name +":"+ Thread.currentThread().getId()+" get lock");

                for (int i=0;i<10;i++){
                    Thread.sleep(1000);
                    System.out.println(name+":"+ Thread.currentThread().getId() + ":工作 "+i+"seconds");
                }

                System.out.println(this.name + "结束工作了;"/* + new Date()*/);

                // 2. 支持过期解锁功能,10秒钟以后自动解锁, 无需调用unlock方法手动解锁
                //lock.lock(10, TimeUnit.SECONDS);

                // 3. 尝试加锁，最多等待20秒，上锁以后10秒自动解锁（实际项目中推荐这种，以防出现死锁）
                //res = yuxinLock.tryLock(20, 100, TimeUnit.SECONDS);
               /* if (res) {
                    System.out.println(this.name + "开始工作了" + new Date());
                    int time = 5000;
                    if (time > 0) {
                        Thread.sleep(time);
                    }
                    System.out.println(this.name + "结束工作了;" + new Date());
                } else {
                    System.out.println(name + "等待超时");
                }*/
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
//                if (res) {
                      yuxinLock.unlock();
//                }
            }
        }

    }
}
